#ifndef HAND_HPP
#define HAND_HPP
#include "Reactor.hpp"
#define SIZE 1024 * 4 // 接收大小
class Handlers
{
public:
    Handlers() {}
    ~Handlers() {}
    void NormalSockfdRead(Connect *conn)
    {
        char inbuffer[SIZE];
        while (true)
        {
            ssize_t n = recv(conn->Sockfd(), inbuffer, SIZE, -1);
            if (n > 0)
            {
                conn->_inbuffer.append(inbuffer, n);
            }
            else
            {
                if (errno == EWOULDBLOCK) // 读完了
                {
                    break;
                }
                else if (errno == EINTR) // 被中断了
                {
                    continue;
                }
                else // 出现了致命错误
                {
                    lg(FATAL, "Happen fatal fail,sockfd: %d,errno: %d", conn->Sockfd(), errno);
                    Expect(conn);
                }
            }
        }
    }
    void NormalSockfdWrite(Connect *conn)
    {
        sleep(1);
        char outbuffer[] = "Hello\n"; // 测试
        ssize_t n = send(conn->Sockfd(), outbuffer, 6, 0);
        if (n < 0)
        {
            lg(FATAL, "Happen fatal fail,sockfd: %d,errno: %d", conn->Sockfd(), errno);
            Expect(conn);
        }
        else
        {
        }
    }
    void Expect(Connect *conn)
    {
        conn->_R->DelConnect(conn->Sockfd());
    }
    void Acceptor(Connect *conn)
    {
        class Addr addr;
        while (true)
        {
            int sockfd = accept(conn->Sockfd(), (struct sockaddr *)&addr, addr.LenPtr());
            if (sockfd > 0)
            {
                lg(INFO, "Get a new connect,sockfd: %d", sockfd);
                conn->_R->AddConnect(sockfd, addr, NORMALSOCKFD);
                break;
            }
            else
            {
                lg(DEBUG,"Accept fail continue...");
            }
        }
    }
};
#endif